package com.yiquan.search.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.mvc.WebContentInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Tyrone
 * @date 2022/3/7 20:59
 */
@Slf4j
@Component
public class LogInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("当前请求URI:{}", requestURI);
        String body = null;
        MDC.put("traceId", UUID.randomUUID().toString());
        if ("POST".equals(request.getMethod())) {
            body = getBodyContent(request);

            log.info("请求体信息为：{}", body);
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        MDC.clear();
    }

    private String getBodyContent(HttpServletRequest request) throws IOException {
        BufferedReader bufferedReader = request.getReader();
        String buffer = "";
        String bodyContent = "";
        while ((buffer = bufferedReader.readLine()) != null) {
            bodyContent += buffer;
        }
        return bodyContent;
    }
}
